// Copyright 2013 Ronald Schlenker, www.technewlogic.de.
// 
// This file is part of Byond.
// 
// Byond is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
// 
// Byond is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Byond.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Linq;
using Byond.Logging;
using Jacobi.Vst.Core;
using Jacobi.Vst.Framework;
using Byond.AudioMidi;
using Byond.Midi;
using Utils.Messaging;

namespace Byond.Vst
{
	public class VstMidi : MidiBase, IVstMidiProcessor
	{
		private readonly IVstHost _host;
		private readonly IVstMidiProcessor _hostMidiProcessor;
		private readonly IEnsembleRunner _ensembleRunner;
		private readonly IUserLogger _logger;

		public VstMidi(IVstHost host)
		{
			_host = host;
			_hostMidiProcessor = _host.GetInstance<IVstMidiProcessor>();
		}

		public override event Action<MidiMessage> OnMessage;
		public event MessageEventHandler SendMessage;

		public int ChannelCount
		{
			get
			{
				return 16;
				// TODO: (auch mal von den VST.Net Samples abschauen)
				//var midiProcessor = _host.GetInstance<IVstMidiProcessor>();
				//return midiProcessor != null ? midiProcessor.ChannelCount : 0;
			}
		}

		/// <summary>This method is called from the VST Host.</summary>
		public void Process(VstEventCollection events)
		{
			events
				.OfType<VstMidiEvent>()
				.Select(it => MidiMessage.TryCreateFromByte(it.Data, it.DeltaFrames))
				.Where(it => it != null)
				.ForEach(RaiseOnMessage);
			//foreach (var vstEvent in events)
			//    Logger.Log("VST Midi In Event: " + vstEvent.Data[0].ToString(), false);
		}

		public override void SendMidiMessage(MidiMessage message)
		{
			base.SendMidiMessage(message);

			//_logger.Log("DltFrm: " + message.HostDeltaFrames);

			// Hier werden die Events von Byond an den Host geschickt
			var vstMidiEvent = new VstMidiEvent(message.HostDeltaFrames, 0, 0, message.ToByte(), 0, 0, true);
			_hostMidiProcessor.Process(new VstEventCollection(new VstEvent[] { vstMidiEvent }));
		}

		private void RaiseOnMessage(MidiMessage message)
		{
			try
			{
				if (OnMessage != null)
					OnMessage(message);
			}
			catch (Exception e)
			{
				_logger.Log("Error in Midi Callback handling: " + e);
				_ensembleRunner.ReportRuntimeError(e);
			}
		}
	}
}